/*
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.anime.logic;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.media.Buffer;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.aileron.anime.ApplicationContext;

import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * @author Aileron
 */
@Singleton
public class SnapshotImpl implements SnapshotAction, SnapshotStatus
{
    @Override
    public void call()
    {
        final Buffer buffer = controller.grabFrame();
        final BufferToImage exchanger = new BufferToImage(
                (VideoFormat) buffer.getFormat());
        final Image image = exchanger.createImage(buffer);
        final BufferedImage bufferedImage = new BufferedImage(width, height,
                Image.SCALE_SMOOTH);
        bufferedImage.getGraphics()
            .drawImage(image, 0, 0, Color.white, null);

        try
        {
            ImageIO.write(bufferedImage, "jpeg", new File("./target/"
                    + (++counter) + ".jpeg"));

            logger.debug("write snapshot : {}", counter);
        }
        catch (final IOException e)
        {
            logger.debug("io-error", e);
        }
    }

    @Override
    public int count()
    {
        return counter;
    }

    @Override
    public synchronized void undo()
    {
        if (counter == -1)
        {
            logger.debug("undo : is not snapshot");
            return;
        }
        logger.debug("undo : {}", counter);

        new File("./target/" + counter + ".jpeg").delete();

        counter -= 1;
    }

    /**
     * @param context
     */
    @Inject
    public SnapshotImpl(final ApplicationContext context)
    {
        this.height = context.height;
        this.width = context.width;
        this.controller = context.grabbingControl;
    }

    private final FrameGrabbingControl controller;
    private volatile int counter = -1;
    private final int height;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final int width;
}
